<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目名称" prop="projName">
        <el-input
          v-model="queryParams.projName"
          placeholder="请输入项目名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" clearable placeholder="请选择状态">
          <el-option
            v-for="item in dict.type.project_invest_status"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="查询月份" prop="searchMonth">
        <el-date-picker
          v-model="queryParams.searchMonth"
          value-format="yyyy-MM"
          type="month"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <TableCard>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['cooperate:projExplore:add']"
          >新增
          </el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table :border="Global.tableShowBorder" v-loading="loading" :data="list">
        <el-table-column label="项目名称" align="center" prop="projName"/>
        <el-table-column label="考察人" align="center" prop="explorers"/>
        <el-table-column label="考察日期" align="center" prop="createTime"></el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
          <template slot-scope="{row}">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(row)"
              v-hasPermi="['cooperate:projExplore:update']"
            >修改
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(row)"
              v-hasPermi="['cooperate:projExplore:delete']"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
    </TableCard>
    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="项目名称" prop="projName">
              <el-input v-model="form.projName" placeholder="请输入项目名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="介绍人" prop="introducer">
              <el-input v-model="form.introducer" placeholder="请输入介绍人"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="介绍人手机" prop="introducerPhone">
              <el-input v-model="form.introducerPhone" placeholder="请输入介绍人手机"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="考察内容" prop="content">
              <el-input v-model="form.content" type="textarea" :rows="6" placeholder="请输入考察内容"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio  v-for="item in dict.type.project_invest_status"
                :key="item.value"
                :label="item.value">{{item.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="考察地点" prop="locationList">
          <el-button type="primary" icon="el-icon-plus" @click="addList('locationList')"></el-button>
        </el-form-item>
        <el-row v-for="(item,index) in form.locationList" :key="'locationList' + index">
          <el-col :span="12">
            <el-form-item label="经度" :prop="'locationList.' + index + '.lon'">
              <el-input v-model="item.lon" placeholder="请输入经度"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="纬度" :prop="'locationList.' + index + '.lat'">
              <div class="flex_hcneter">
                <el-input class="flex_flex" v-model="item.lat" placeholder="请输入纬度"/>
                <el-button type="primary" style="margin-left:15px;" @click="amapSelect(item,index)">获取位置</el-button>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="详细地址" :prop="'locationList.' + index + '.location'">
              <el-input v-model="item.location" placeholder="请输入详细地址"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="图片">
              <imageUpload @fileSuccess="(e)=>fileSuccess(e,index)"
                :fileType="['bmp','jpg','png','gif',]" returnData="Array" fileName="files" :fileData="{'bizType':'projExplore',}"
                action="/oa-pcapi/cooperate/file/uploadAtt"
                v-model="item.images" :limit="100"></imageUpload>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="附件" >
              <el-button type="primary" icon="el-icon-plus" @click="addList('locationList',index)"></el-button>
              <el-button style="margin-left:10px;" v-if="form.locationList.length > 1"
                  @click="delList(index,'locationList')" type="primary" icon="el-icon-minus"></el-button>
            </el-form-item>
          </el-col>
          <div v-for="(item1,index1) in item.attList" :key="'attList' + index1">
            <el-col :span="24">
              <!--
              :rules="{
                required: true, message: '文件名称不能为空', trigger: 'blur'
              }" -->
              <el-form-item label="文件名称"
              >
                <el-input v-model="item1.fileName"  placeholder="请输入文件名称"/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="文件路径"
              >
                <div class="flex_hcneter">
                  <FileUpload :limit="1"  v-model="item1.url"
                  :fileType="null" returnData="Array"
                  fileName="files" :fileData="{'bizType':'projExplore',}"
                  action="/oa-pcapi/cooperate/file/uploadAtt" btnName="选择"></FileUpload>
                  <el-button style="margin-left:10px;"
                  @click="delList(index1,'locationList',index)" type="primary" icon="el-icon-minus"></el-button>
                </div>
              </el-form-item>
            </el-col>
          </div>
        </el-row>
        <el-form-item label="考察人员" prop="explorerList"><el-button type="primary" icon="el-icon-plus" @click="addList('explorerList')"></el-button></el-form-item>
        <el-row v-for="(item,index) in form.explorerList" :key="'explorerList' + index">
          <el-col :span="12">
            <el-form-item label="用户"
            :prop="'explorerList.' + index + '.userId'"
            :rules="{
              required: true, message: '用户不能为空', trigger: 'blur'
            }">
              <div class="flex_hcneter">
                <el-select v-model="item.userId" filterable clearable placeholder="请选择参会人员">
                  <el-option
                    v-for="item1 in userList"
                    :key="item1.userId"
                    :label="item1.nickName"
                    :value="Number(item1.userId)">
                  </el-option>
                </el-select>
                <el-button style="margin-left:10px;" v-if="form.explorerList.length > 1"
                @click="delList(index,'explorerList')" type="primary" icon="el-icon-minus"></el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 地图弹窗 -->
    <mapLog ref="mapLogs" @mapSubmit="mapSubmit" :formObj="form" isDetail :formType="{
      'longitude':'lon',
      'latitude':'lat',
      'details':'location',
    }"></mapLog>
  </div>
</template>

<script>
import {listProjExplore, getProjExplore, addProjExplore, updateProjExplore, delProjExplore} from "@/api/collaWorryFree/projectInvest";
import {userListAll} from "@/api/system/user";
import { timesToYyMmDd1 } from '@/utils/time';
import mapLog from "@/components/mapLog/index";
export default {
  name: "ProjectInvest",
  dicts: ['project_invest_status','project_invest_type',],
  components: { mapLog, },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      list: [],
      // 弹出层标题
      title: "",
        // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projName: undefined,searchMonth: undefined,
        status: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        projName: [ {required: true, message: "项目名称不能为空", trigger: "blur"} ],
        content: [ {required: true, message: "考察内容不能为空", trigger: "blur"} ],
        status: [ {required: true, message: "状态不能为空", trigger: "change"} ],
        locationList: [ {required: true, message: "考察地点不能为空", trigger: "change"} ],
        explorerList: [ {required: true, message: "考察人员不能为空", trigger: "change"} ],
      },
      userList:[],//用户数据
      mapIndex:'',//地图组件下标
    };
  },
  created() {
      this.getList();
  },
  methods: {
    amapSelect(e,index){//地图打开
      this.mapIndex = index
      this.$refs.mapLogs.mapLoad(e)
    },
    //地图选择保存
    mapSubmit(forms){
      let form = {...this.form}
      form.locationList[this.mapIndex] = {...forms}
      this.form = {...form}
    },
    addList(ziduan,index){//添加列表
      if(index || index === 0) {
        let form = JSON.parse(JSON.stringify(this.form))
        if(!form[ziduan][index].attList) form[ziduan][index].attList = []
        form[ziduan][index].attList.push({fileName:null,url:null,})
        this.form = JSON.parse(JSON.stringify(form))
        console.log('this.form',this.form)
      }else{
        this.form[ziduan].push({})
      }
    },
    delList(index,ziduan,index1){//删除列表
      if(index1 || index1 === 0) {
        let form = {...this.form}
        form[ziduan][index1].attList.splice(index,1)
        this.form = {...form}
      }else{
        this.form[ziduan].splice(index,1)
      }
    },
    async userListAll(){//获取所有用户
      let res = await userListAll()
      let data = res.data || []
      this.userList = data.map(item=>{
        return{...item,userId:item.userId + ''}
      })
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      let queryParams = {...this.queryParams}
      let dateRange = queryParams.dateRange || []
      if(dateRange.length) {
        queryParams.meetingTimeStart = dateRange[0]
        queryParams.meetingTimeEnd = dateRange[1]
      }
      delete queryParams.dateRange
      listProjExplore(queryParams).then(response => {
        this.list = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      // this.reset();
    },
    // 表单重置
    reset() {
      this.form = {status:'1',locationList:[{}],explorerList:[{}],};
      // this.resetForm("form");
      this.userListAll()
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    fileSuccess(e,index){//图片上传成功
      console.log('fileSuccess',e)
      let imageList = e || []
      this.form.locationList[index].imgList = imageList.map(item=>{
        return{...item,fileName:item.name,}
      })
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加会议纪要";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getProjExplore(id).then(response => {
        let data = response.data || {};
        let locationList = data.locationList || [{}]
        this.form = {
          ...data,
          locationList:locationList.map(item=>{
            let imgList = item.imgList || []
            let attList = item.attList || []
            let imgs = imgList.map(item=>item.url)
            return {
              ...item,images:imgs.toString(),
              imgList,attList,
            }
          }),
          explorerList:data.explorerList || [{}],
        }
        this.open = true;
        this.title = "修改会议纪要";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let form = {...this.form}
          if (this.form.id != undefined) {
            updateProjExplore(form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProjExplore(form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id || this.ids
      this.$modal.confirm('是否确认删除该数据项？').then(function () {
          return delProjExplore(id);
      }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    }
  }
};
</script>
